package cn.levi.excel.validate;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.StrUtil;
import cn.levi.excel.annotation.Excell;
import cn.levi.excel.annotation.ExcellValidate;
import cn.levi.excel.module.StateBo;
import java.lang.reflect.Field;
import java.util.Map;
import org.springframework.stereotype.Component;

/**
 * 校验字符长度
 *
 * @author lei
 * @since 2024/10/16
 */
@Component
public class ValidateLength implements ValidateExcelImport{

	/**
	 * 校验是否通过
	 *
	 * @param field         字段
	 * @param excellDataRow excel一行数据 ；
	 *                      其中key已经转还为bean属性 ；
	 *                      value为excel的原始数据且全为字符串类型，校验值时要注意
	 * @return
	 */
	@Override
	public StateBo validate(Field field, Map<String, Object> excellDataRow) {
		String fieldValue = getFieldValue(field, excellDataRow);
		ExcellValidate annotation = AnnotationUtil.getAnnotation(field, ExcellValidate.class);
		Excell excell = AnnotationUtil.getAnnotation(field, Excell.class);
		if (!annotation.enable()) {
			return StateBo.success();
		}
		return StrUtil.isBlank(fieldValue) || fieldValue.length() <= annotation.length() ? StateBo.success() : StateBo.fail(StrUtil.format("{}超过长度限制", excell.value()));
	}
}
